/**
 * 定义字典模块
 */
(function(window, angular, undefined){

	var domainModule = angular.module('water.entity.domain',['waterCommon']);
	
	domainModule.service('$domainService',function($waterDataCommon){
		
		/**
		 * 系统字典组件，查询字典表
		 * 查询单个字典
		 * {
		 *  data:'行政区划',
		 *  filterObject:filterObject //json格式，但是是字符串类型，如果要查下一级，"{\"S_PID\":\""+sid+"\"}"，sid就是父级别的sid，如果不查，则为空
		 * }
		 */
		this.getList = function(domainName,parentId){
			var filterObject = "";
			if(parentId){
				filterObject = "{\"S_PID\":\""+parentId+"\"}"
			}
			var promise = $waterDataCommon.post("/form/DATA_DEFULATDOMAIN/getDomains",{data:domainName,filterObject:filterObject});
			return promise;
		}
		/**
		 * data{
		 * 	DOMAINCAPTION:'氨氮',
		 *  DOMAINCODE:'060',
		 *  ORDER:1,
		 *  UNIT:mg/L
		 * }
		 */
		this.createDomainItem = function(domainName,data){
			var domainData = {
					DOMAINID:NewGuid(),
					FIELD_ISNEW:true,
					_IS_DOMAIN_TRUE:true,
					DOMAINNAME:domainName,
					DOMAINCAPTION:data.S_DOMAINCAPTION,
					DOMAINCODE:data.S_DOMAINCODE,
					ORDER:data.I_ORDER,
					UNIT:data.S_UNIT,
					ISCHILD:"1",
					JB:"1",
					ACTIVITISAVE:"0",
					ACTIVITIKEY:"",
			};
			
			var data = toJSONString(domainData);
			var promise = $waterDataCommon.post("/form/DATA_DEFULATDOMAIN/save",{data:data});
			return promise;
		}
		/**
		 * data{
		 * 	DOMAINCAPTION:'氨氮',
		 *  DOMAINCODE:'060',
		 *  ORDER:1,
		 *  UNIT:mg/L
		 * }
		 */
		this.updateDomainItem = function(domainName,data){
			var domainData = {
					DOMAINID:data.S_ID,
					FIELD_ISNEW:false,
					_IS_DOMAIN_TRUE:true,
					DOMAINNAME:domainName,
					DOMAINCAPTION:data.S_DOMAINCAPTION,
					DOMAINCODE:data.S_DOMAINCODE,
					ORDER:data.I_ORDER,
					UNIT:data.S_UNIT,
					ISCHILD:"1",
					JB:"1",
					ACTIVITISAVE:"0",
					ACTIVITIKEY:"",
			};
			
			var data = toJSONString(domainData);
			var promise = $waterDataCommon.post("/form/DATA_DEFULATDOMAIN/save",{data:data});
			return promise;
		}
		/**
		 * 自定义字典组件，查询自定义业务表
		 * tableName 数据源表
		 * keyField 键字段
		 * valueField 值字段
		 * parentField 如果有级联关系，这个字段就是父级别的字段
		 * pid 父级别id
		 */
		this.getCustomersList = function(tableName,keyField,valueField,parentField,pid){
			var filterObject = "";
			var promise = $waterDataCommon.post("/CustomersDomain/getList",{
					tableName:tableName,
					keyField:keyField,
					valueField:valueField,
					parentField:parentField,
					pid:pid
				});
			return promise;
		}
		
		function S4() 
		{   
		   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);   
		}    
		
		function NewGuid() 
		{   
		   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());   
		}
		
		function toJSONString(jsonObj){
			var jStr = "{ ";
		    for(var item in jsonObj){
		        jStr += "\""+item+"\":\""+jsonObj[item]+"\",";
		    }
		    if(jStr.length >= 2){
		    	jStr = jStr.substring(0,jStr.length - 1);
		    }
		   
		    jStr += " }";
			return jStr;  
		}
	})
}(window, angular));